<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div style="margin-bottom: 10px;">
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入手机号" v-model="listQuery.mobile">
      </el-input>
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="确认手机号" v-model="confirmMobile">
      </el-input>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="findUser">充值</el-button>
      <div>
        <div style="font-size:12px;color:red;width:900px;margin-bottom:10px;margin-top:10px;display:inline;">{{remindValue}}</div>
        <div style="font-size:18px;color:blue;width:900px;margin-bottom:10px;margin-top:10px;display:inline;" @click="payFive">点我支付</div>
      </div>
    </div>
    <div style="margin-bottom: 10px;">
      <el-date-picker clearable class="filter-item" value-format="yyyy-MM-dd HH:mm:ss" v-model="tempAddTime" type="datetimerange" :picker-options="pickerOptions" range-separator="至" start-placeholder="起始日期" end-placeholder="结束日期" align="right">
      </el-date-picker>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload" :loading="downloadLoading">导出充值记录</el-button>
    </div>
    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" width="100px" label="ID" prop="id" sortable>
      </el-table-column>
      <el-table-column align="center" label="类型" prop="type">
        <template slot-scope="scope">
          <el-tag>{{typeDic[scope.row.type]}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="充值原因" prop="modifyReason">
      </el-table-column>

      <el-table-column align="center" label="充值积分" prop="modifyIntegral">
      </el-table-column>

      <el-table-column align="center" label="充值时间" prop="modifyTime">
      </el-table-column>

      <el-table-column align="center" label="支付方式" prop="payType">
        <template slot-scope="scope">
          <el-tag>{{payTypeDic[scope.row.payType]}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="用户昵称" prop="nickname">
      </el-table-column>

      <el-table-column align="center" label="用户手机号码" prop="mobile">
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 用户信息查询 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogChargeFormVisible">
      <el-card class="box-card">
        <h3>用户信息</h3>
        <el-form :rules="rules" ref="dataForm" :model="dataForm" label-position="right" label-width="100px">
          <el-form-item label="用户姓名:" prop="username">
            <span v-text="dataForm.username" style="color:#3cd94f;">
            </span>
          </el-form-item>
          <el-form-item label="手机号码:" prop="mobile">
            <span v-text="dataForm.mobile" style="color:#3cd94f;">
            </span>
          </el-form-item>
          <el-form-item label="性别:" prop="gender">
            <span style="color:#3cd94f;">{{genderDic[dataForm.gender]}}</span>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="box-card">
        <h3>充值信息</h3>
        <el-form :rules="rules" ref="walletRecoed" :model="walletRecoed" label-position="right" label-width="100px">
          <el-form-item label="充值单号" prop="recordSn">
            <el-input v-model="walletRecoed.recordSn" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="积分数量" prop="modifyIntegral">
            <el-input-number v-model="walletRecoed.modifyIntegral" :min="1" :step="1"></el-input-number>
          </el-form-item>
          <el-form-item label="充值原因" prop="modifyReason">
            <el-input v-model="walletRecoed.modifyReason" type="textarea" :rows="2" autosize></el-input>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="box-card">
        <h3>支付方式</h3>
        <div id="example-4" style="margin-left:50px">
          <template>
            <el-radio v-model="walletRecoed.payType" label="2"> <img :src="wxpay" alt="" class="abimg"></el-radio>
            <el-radio v-model="walletRecoed.payType" label="1"> <img :src="zhifubaopay" alt="" class="abimg"></el-radio>
          </template>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleChargeCancel">取消</el-button>
        <el-button type="primary" @click="handleCharge" v-bind:disabled="chargeButton">充值</el-button>
      </div>
    </el-dialog>
    <!-- 添加对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rule2" ref="userForm" :model="userForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="userForm.mobile" :readonly="true"></el-input>
        </el-form-item>
        <!--<el-form-item label="密码" prop="password">-->
        <!--<el-input type="password" v-model="userForm.password" auto-complete="false"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="确认密码" prop="checkPassword">-->
        <!--<el-input type="password" v-model="userForm.checkPassword" auto-complete="off"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="性别" prop="gender">
          <el-select v-model="userForm.gender">
            <el-option label="未知" :value="0">
            </el-option>
            <el-option label="男" :value="1">
            </el-option>
            <el-option label="女" :value="2">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker v-model="userForm.birthday" type="date" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用户等级" prop="userLevel">
          <el-select v-model="userForm.userLevel">
            <el-option label="普通用户" :value="0">
            </el-option>
            <el-option label="VIP用户" :value="1">
            </el-option>
            <el-option label="高级VIP用户" :value="2">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status">
            <el-option label="可用" :value="0">
            </el-option>
            <el-option label="禁用" :value="1">
            </el-option>
            <el-option label="注销" :value="2">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="createData" v-bind:disabled="createUserButton">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog title="微信支付" :visible.sync="qrDialogStatus" :close-on-click-modal=false width="250px" :before-close="cancelPay">
      <vue-qr :text="qrConfig.value" :size="200" :margin="0"></vue-qr>
      <h3 style="color :red">注意：请在十五分钟内完成支付！支付成功后系统会自动关闭二维码！</h3>
    </el-dialog>
    <!-- 添加对话框 -->
    <el-dialog title="支付宝支付" :visible.sync="alipayDialogStatus" :close-on-click-modal=false width="250px" :before-close="cancelAliPay">
      <vue-qr :text="aliQrConfig.value" :size="200" :margin="0"></vue-qr>
      <h3 style="color :red">注意：请在十五分钟内完成支付！支付成功后系统会自动关闭二维码！</h3>
    </el-dialog>
  </div>
</template>

<script>
import {
  checkUserName,
  createNewUser,
  createUser,
  getList,
  readUser,
  chargeByAliPay,
  queryalipaystatus,
  orderTotallist,
  payFive
} from '@/api/user'
import store from '@/store'
import VueQr from 'vue-qr'
import wxpay from '@/assets/image/wxpay.png'
import zhifubaopay from '@/assets/image/zhifubaopay.png'

export default {
  name: 'User',
  components: { VueQr },
  data() {
    var validUserName = (rule, value, callback) => {
      this.userName.userName = value
      checkUserName(this.userName)
        .then(response => {
          var validFlag = response.data.data.validFlag
          if (validFlag) {
            callback()
          } else {
            callback(new Error('用户名已存在！'))
          }
        })
        .catch(() => {
          console.log('请求超时！')
        })
    }
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号码'))
      } else {
        var reg = /^1[3456789]\d{9}$/
        if (!reg.test(value)) {
          callback(new Error('请输入有效的手机号码'))
        }
      }
      callback()
    }
    var validatemodifyIntegral = (rule, value, callback) => {
      var reg = /^[0-9]*$/
      if (value === '') {
        callback(new Error('请输入充值数量'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入有效的值'))
      } else {
        callback()
      }
    }
    return {
      wxpay,
      remindValue: '',
      zhifubaopay,
      confirmMobile: '',
      list: null,
      total: undefined,
      listLoading: true,
      values: undefined,
      listQuery: {
        page: 1,
        limit: 20,
        mechanismId: store.getters.mechanismId,
        mobile: '',
        sort: 'modify_time',
        order: 'desc'
      },
      userName: {
        page: 1,
        limit: 20,
        mobile: '',
        sort: '',
        order: ''
      },
      orderSn: {
        orderSn: ''
      },
      dataForm: {
        username: '',
        mobile: '',
        gender: ''
      },
      walletRecoed: {
        userId: undefined,
        recordSn: '',
        modifyIntegral: '',
        modifyResource: store.getters.mechanismId,
        modifyReason: '',
        payType: '2',
        type: '1'
      },
      userForm: {
        id: undefined,
        username: '',
        mobile: undefined,
        // password: undefined,
        // checkPassword: undefined,
        gender: 0,
        firstMechanism: store.getters.mechanismId,
        userLevel: 0,
        birthday: undefined,
        status: 0
      },
      qrConfig: {
        value: ''
      },
      aliQrConfig: {
        value: ''
      },
      alipayInfo: '',
      textMap: {
        create: '创建用户信息',
        userCharge: '用户充值'
      },
      downloadLoading: false,
      dialogChargeFormVisible: false,
      dialogFormVisible: false,
      attributeVisiable: false,
      tempAddTime: undefined,
      chargeButton: false,
      createUserButton: false,
      dialogStatus: '',
      qrDialogStatus: false,
      alipayDialogStatus: false,
      pickerOptions: {
        shortcuts: [
          {
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '前天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      rules: {
        modifyIntegral: [
          { required: true, message: '充值数量不能为空', trigger: 'blur' },
          { validator: validatemodifyIntegral, trigger: 'blur' }
        ],
        modifyReason: [{ required: true, message: '充值原因不能为空', trigger: 'blur' }]
      },
      rule2: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { validator: validUserName, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ]
      },
      genderDic: ['未知', '男', '女'],
      typeDic: ['', '充值', '消费'],
      payTypeDic: ['', '支付宝', '微信', '其他']
    }
  },
  created() {
    // console.log(store.getters.mechanismId)
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getList(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.remindValue = response.data.data.remindValue
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },

    payFive() {
      var recordSn = this.createRecordSn()
      var payFiveWalletRecord = {
        modifyResource: store.getters.mechanismId,
        recordSn: recordSn
      }
      payFive(payFiveWalletRecord).then(response => {
        var codeUrl = response.data.data.codeURL
        this.qrConfig.value = codeUrl
        this.qrDialogStatus = true
        this.timeOut = setTimeout(() => {
          this.checkChargeStatuss(recordSn)
        }, 5000)
      })
    },

    handleDownload() {
      if (this.tempAddTime !== undefined && this.tempAddTime !== null) {
        this.listQuery.addTime = this.tempAddTime.toString()
      } else {
        this.$message({
          message: '提示，请选择时间区间',
          type: 'warning'
        })
        return
      }
      import('@/vendor/Export2Excel').then(excel => {
        orderTotallist(this.listQuery).then(response => {
          const tHeader = ['用户ID', '充值原因', '充值积分', '实际支付', '充值时间', '支付方式', '用户昵称', '用户号码']
          const filterVal = [
            'id',
            'modifyReason',
            'modifyIntegral',
            'actualPayment',
            'modifyTime',
            'payTypes',
            'nickname',
            'mobile'
          ]
          const list = response.data.data.items
          excel.export_json_to_excel2(tHeader, list, filterVal, '充值记录')
          this.downloadLoading = false
        })
      })
    },

    filterLevel: function(value, row) {
      return row.payType === value
    },
    createData() {
      this.$refs['userForm'].validate(valid => {
        if (valid) {
          this.createUserButton = true
          createNewUser(this.userForm).then(response => {
            this.dialogFormVisible = false
            this.createUserButton = false
            if (response.data.data !== 'fail') {
              this.resetUserForm()
              this.walletRecoed.userId = response.data.data.id
              this.dataForm.username = response.data.data.username
              this.dataForm.mobile = response.data.data.mobile
              this.dataForm.gender = response.data.data.gender
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 800
              })
              this.$confirm('是否立即充值?', '提示', {
                confirmButtonText: '充值',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(() => {
                  this.dialogStatus = 'userCharge'
                  this.dataForm = response.data.data
                  this.dialogChargeFormVisible = true
                  this.walletRecoed.userId = response.data.data.id
                  this.walletRecoed.recordSn = this.createRecordSn()
                  this.values = response.data.data.values
                })
                .catch(() => {
                  this.resetForm()
                })
            } else {
              this.$confirm('创建失败，此用户已经绑定，请根据手机号充值！', '提示', {
                type: 'warning'
              })
                .then(() => {})
                .catch(() => {})
            }
          })
        }
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetmobile() {
      this.confirmMobile = ''
    },
    resetForm() {
      this.dataForm = {
        username: '',
        mobile: '',
        gender: ''
      }
      this.walletRecoed = {
        userId: undefined,
        recordSn: '',
        modifyIntegral: '',
        modifyReason: '',
        modifyResource: store.getters.mechanismId,
        payType: '2',
        type: '1'
      }
    },
    resetUserForm() {
      this.userForm = {
        id: undefined,
        username: '',
        mobile: '',
        // pass: undefined,
        // checkPass: undefined,
        gender: 0,
        userLevel: 0,
        birthday: undefined,
        status: 0
      }
    },
    handleCharge() {
      this.$refs['walletRecoed'].validate(valid => {
        if (valid) {
          if (this.walletRecoed.payType === '2') {
            this.chargeButton = true
            this.fullscreenLoading = true
            createUser(this.walletRecoed).then(response => {
              var codeUrl = response.data.data.codeURL
              this.qrConfig.value = codeUrl
              this.qrDialogStatus = true
              this.timeOut = setTimeout(() => {
                this.checkChargeStatus()
              }, 5000)
            })
          } else if (this.walletRecoed.payType === '1') {
            // this.chargeButton = true
            // this.fullscreenLoading = true
            chargeByAliPay(this.walletRecoed)
              .then(response => {
                var data = response.data
                if (data.errno === 0) {
                  var codeUrl = data.data
                  this.aliQrConfig.value = codeUrl
                  this.alipayDialogStatus = true
                  this.chargeButton = true
                  this.timeOut = setTimeout(() => {
                    this.queryalipaystatus()
                  }, 5000)
                }
              })
              .catch(err => {
                console.log(err)
              })
          }
        }
      })
    },
    cancelPay(done) {
      this.$notify({
        title: '提示',
        message: '微信正在支付中，不允许关闭！强行关闭会造成积分充值失败！支付成功后，二维码自动关闭！',
        type: 'warning',
        duration: 8000
      })
    },
    cancelAliPay(done) {
      this.$notify({
        title: '提示',
        message: '支付宝正在支付中，不允许关闭！强行关闭会造成积分充值失败！支付成功后，二维码自动关闭！',
        type: 'warning',
        duration: 8000
      })
    },
    checkChargeStatuss(orderSn) {
      var orderSns = orderSn
      queryalipaystatus({ orderSn: orderSns }).then(response => {
        var orderStatus = response.data.data.orderStatus
        if (orderStatus === 'SUCCESS') {
          this.qrConfig.value = ''
          this.qrDialogStatus = false
          this.timeOut = ''
          this.dialogChargeFormVisible = false
          this.fullscreenLoading = false
          this.chargeButton = false
          this.resetmobile()
          this.$alert('支付成功，请联系微信号：ailianSQ', '联系人微信号', {
            confirmButtonText: '确定',
            callback: action => {}
          })
        } else {
          this.timeOut = setTimeout(() => {
            this.checkChargeStatuss(orderSn)
          }, 3000)
        }
      })
    },
    checkChargeStatus() {
      if (this.walletRecoed.recordSn !== '') {
        this.orderSn.orderSn = this.walletRecoed.recordSn
        queryalipaystatus(this.orderSn).then(response => {
          var orderStatus = response.data.data.orderStatus
          if (orderStatus === 'SUCCESS') {
            this.qrConfig.value = ''
            this.qrDialogStatus = false
            this.timeOut = ''
            this.resetForm()
            this.dialogChargeFormVisible = false
            this.getList()
            this.fullscreenLoading = false
            this.chargeButton = false
            this.resetmobile()
            this.$notify({
              title: '成功',
              message: '充值成功',
              type: 'success',
              duration: 1000
            })
          } else {
            this.timeOut = setTimeout(() => {
              this.checkChargeStatus()
            }, 3000)
          }
        })
      }
    },
    queryalipaystatus() {
      if (this.walletRecoed.recordSn !== '') {
        this.orderSn.orderSn = this.walletRecoed.recordSn
        queryalipaystatus(this.orderSn)
          .then(response => {
            var orderStatus = response.data.data.orderStatus
            if (orderStatus === 'SUCCESS') {
              this.timeOut = ''
              this.aliQrConfig.value = ''
              this.resetForm()
              this.dialogChargeFormVisible = false
              this.alipayDialogStatus = false
              this.getList()
              this.fullscreenLoading = false
              this.chargeButton = false
              this.$notify({
                title: '成功',
                message: '充值成功',
                type: 'success',
                duration: 3000
              })
            } else if (orderStatus === 'WAIT_PAY') {
              this.timeOut = setTimeout(() => {
                this.queryalipaystatus()
              }, 3000)
            }
          })
          .catch(() => {
            this.timeOut = ''
            this.resetForm()
            this.dialogChargeFormVisible = false
            this.alipayDialogStatus = false
            this.getList()
            this.fullscreenLoading = false
            this.chargeButton = false
            this.$notify({
              title: '错误',
              message: '充值失败',
              type: 'error',
              duration: 1000
            })
          })
      }
    },
    handleFilter() {},
    handleChargeCancel() {
      this.resetForm()
      this.dialogChargeFormVisible = false
    },
    findUser() {
      var reg = /^1[3456789]\d{9}$/
      if (this.listQuery.mobile === '') {
        this.$message({
          message: '请输入要充值的号码',
          type: 'warning'
        })
        return false
      } else if (!reg.test(this.listQuery.mobile)) {
        this.$message({
          message: '请输入有效的手机号码',
          type: 'warning'
        })
        return false
      } else if (this.listQuery.mobile !== this.confirmMobile) {
        this.$message({
          message: '两次输入的手机号码不一致！',
          type: 'warning'
        })
        return false
      }
      readUser(this.listQuery).then(response => {
        if (response.data.data.num > 0) {
          this.dialogStatus = 'userCharge'
          this.dialogChargeFormVisible = true
          this.dataForm = response.data.data.user
          this.walletRecoed.userId = response.data.data.user.id
          this.walletRecoed.recordSn = this.createRecordSn()
          this.values = response.data.data.values
        } else {
          this.$confirm('用户不存在, 是否新建用户?', '提示', {
            confirmButtonText: '新建',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              this.dialogStatus = 'create'
              this.userForm.mobile = this.listQuery.mobile
              this.dialogFormVisible = true
              this.$nextTick(() => {
                this.$refs['userForm'].clearValidate()
              })
            })
            .catch(() => {
              this.resetUserForm()
            })
        }
      })
    },
    createRecordSn() {
      var date = new Date()
      var Y = date.getFullYear()
      var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      var ss = date.getMilliseconds()
      if (ss < 10) {
        ss = '00' + ss
      } else if (ss < 100) {
        ss = '0' + ss
      }
      return Y.toString() + M.toString() + D.toString() + h.toString() + m.toString() + s.toString() + ss.toString()
    }
  }
}
</script>
<style>
.alipay {
  width: 200rect;
  height: 100rect;
  background-color: red;
}
.rra {
  margin-bottom: 100px;
}
.abimg {
  margin-bottom: -15px;
  height: 40px;
}
</style>
